import { AppDispatch } from './../index';
import { getResultsAPI, getSuggetsAPI } from '@/api/search';
import { ActionType } from '../reducer/search';

export const getSuggetsAction = (q: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getSuggetsAPI(q);
    const newOptions = res.data.options.filter((item: string) => !!item);
    dispatch({ type: 'search/saveSuggests', payload: newOptions });
  };
};

export const clearSuggestAction = (): ActionType => {
  return { type: 'search/saveSuggests', payload: [] };
};

export const getResultsAction = (q: string, page?: number) => {
  return async (dispatch: AppDispatch) => {
    const res = await getResultsAPI(q, page);
    dispatch({ type: 'search/saveResults', payload: res.data });
  };
};
export const clearResultsAction = (): ActionType => {
  return { type: 'search/clearResults' };
};
